﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using GroundWater.Data;
using GroundWater.BusinessActions;
using WellTable = GroundWater.Data.InfoDataSet.WellsDataTable;
using WellRow = GroundWater.Data.InfoDataSet.WellsRow;

namespace GroundWater.Basedata
{
    public partial class WellQuery1 : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SiteUtil.Validate(this, "水井信息维护");
        }
        protected void RowDataBound(object sender, GridViewRowEventArgs args)
        {
            GridView gridView = (GridView)sender;

            if (gridView.SortExpression.Length > 0)
            {
                int cellIndex = -1;
                foreach (DataControlField field in gridView.Columns)
                {
                    if (field.SortExpression == gridView.SortExpression)
                    {
                        cellIndex = gridView.Columns.IndexOf(field);
                        break;
                    }
                }

                if (cellIndex > -1)
                {
                    if (args.Row.RowType == DataControlRowType.Header)
                    {
                        //  this is a header row,
                        //  set the sort style
                        args.Row.Cells[cellIndex].CssClass +=
                            (gridView.SortDirection == SortDirection.Ascending
                            ? " sortasc" : " sortdesc");
                    }
                }
            }

            if (args.Row.RowType == DataControlRowType.DataRow)
            {
                if (args.Row.RowIndex > -1)
                {
                    if (args.Row.Cells[10].Controls.Count > 0)
                    {
                        LinkButton btnDelete = args.Row.Cells[10].Controls[0] as LinkButton;
                        if (btnDelete != null && btnDelete.Text == "删除")
                        {
                            btnDelete.OnClientClick = "return confirm('您是否确认删除此项？');";
                        }
                    }
                }
            }
        }

        protected void odsWells_Deleting(object sender, ObjectDataSourceMethodEventArgs e)
        {
            e.InputParameters["id"] = e.InputParameters["Code"];
            e.InputParameters.Remove("Code");

            int cnt = Monitoring.FetchRowCount(e.InputParameters["id"].ToString(), DateTime.Now.AddYears(-2).ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"));

            if (cnt > 0)
            {
                e.Cancel = true;
                sm.RegisterDataItem(updPanel, "1");//updPanel
            }
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            GridViewRow row = ((LinkButton)sender).Parent.Parent as GridViewRow;
            string wellId = this.gvWells.DataKeys[row.RowIndex].Value.ToString();
            SetFields(wellId);

            updPnl.Update();
            txtWellCode.Enabled = false;
            mdlPopup.Show();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (txtWellCode.Text.Trim().Length == 0 || txtWellName.Text.Length == 0) return;

            string wellId = this.hidWellCode.Value;// this.ViewState["WellId"] as String;
            InfoDataSet well = GetFields(wellId);
            if (well == null)
            {
                lblJavaScript.Text = "<script type=\"text/javascript\">alert('已存在代码为" + txtWellCode.Text.Trim() + " 的水井。');</script>";
                return;
            }

            Well.Update(well, false, true, new string[] { well.Wells.TableName });

            gvWells.DataBind();

            updPanel.Update();
            //this.ViewState.Remove("WellId");
            hidWellCode.Value = "";

            ClearFields();
        }

        private void ClearFields()
        {
            txtBTUAddress.Text = "";
            txtDepth.Text = "";
            txtLongitude.Text = "";
            txtLatitude.Text = "";
            txtSectionPlane.Text = "";
            txtShaftSinkingDate.Text = "";
            txtSIMCard.Text = "";
            txtWellCode.Text = "";
            txtWellName.Text = "";
            txtAltitude.Text = "";
            txtSequenceNumber.Text = "";

            //this.ViewState["WellId"] = "";
            this.hidWellCode.Value = "";
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            ClearFields();
            txtWellCode.Enabled = true;
            mdlPopup.Show();

        }

        private void SetFields(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                WellRow row = Well.GetById(id, false);
                if (!row.IsBTUAddressNull())
                {
                    txtBTUAddress.Text = row.BTUAddress;
                }

                if (!row.IsDepthNull())
                {
                    txtDepth.Text = row.Depth.ToString();
                }
                if (!row.IsLongitudeNull())
                {
                    txtLongitude.Text = row.Longitude.ToString();
                }
                if (!row.IsLatitudeNull())
                {
                    txtLatitude.Text = row.Latitude.ToString();
                }

                if (!row.IsSectionPlaneNull())
                {
                     txtSectionPlane.Text = row.SectionPlane;
                }
                if (!row.IsShaftSinkingDateNull())
                {
                    txtShaftSinkingDate.Text = row.ShaftSinkingDate.ToString("yyyy-MM-dd"); 
                }

                if (!row.IsBTUAddressNull())
                {
                    txtSIMCard.Text = row.SIMCard;
                }
                txtWellCode.Text = row.Code;
                txtWellName.Text = row.Name;
                txtAdministrativeDivisionsCode.Text = row.AdministrativeDivisionsCode;
                txtDesignYearlyWaterQuantity.Text = row.DesignYearlyWaterQuantity.ToString();
                txtFunctionRegionCode.Text = row.FunctionRegionCode;
                txtResourceRegionCode.Text = row.ResourceRegionCode;
                txtWaterSource.Text = row.WaterSource;


                txtMaximumWaterlevel.Text = row.MaximumWaterlevel == 0 ? System.Configuration.ConfigurationManager.AppSettings["MaximumWaterlevel"] : row.MaximumWaterlevel.ToString();
                txtMinimumWaterlevel.Text = row.MinimumWaterlevel == 0 ? System.Configuration.ConfigurationManager.AppSettings["MinimumWaterlevel"] : row.MinimumWaterlevel.ToString();

                if (!row.IsAdministrationNull())
                {
                    txtAdministration.Text = row.Administration;
                }

                if (!row.IsDesignFlowRateNull())
                {
                    txtDesignFlowRate.Text = row.DesignFlowRate.ToString();
                }
                if (!row.IsDiameterNull())
                {
                    txtDiameter.Text = row.Diameter.ToString();
                }

                if (!row.IsDynamicLevelNull())
                {
                    txtDynamicLevel.Text = row.DynamicLevel.ToString();
                }

                if (!row.IsLandformNull())
                {
                    txtLandform.Text = row.Landform;
                }

                if (!row.IsProjectRuningStateNull())
                {
                    txtProjectRuningState.Text = row.ProjectRuningState;
                }
                if (!row.IsPumpTypeNull())
                {
                    txtPumpType.Text = row.PumpType;
                }

                if (!row.IsRemoveEquipmentNull())
                {
                    txtRemoveEquipment.Text = row.RemoveEquipment;
                }

                if (!row.IsStaticLevelNull())
                {
                    txtStaticLevel.Text = row.StaticLevel.ToString();
                }

                if (!row.IsWaterQualityNull())
                {
                    txtWaterQuality.Text = row.WaterQuality;
                }

                if (!row.IsAltitudeNull())
                {
                    txtAltitude.Text = row.Altitude.ToString();
                }

                if (!row.IsSequenceNumberNull())
                {
                    txtSequenceNumber.Text = row.SequenceNumber.ToString();
                }

                

                //this.ViewState["WellId"] = id;
                this.hidWellCode.Value = id;
            }
        }

        private GroundWater.Data.InfoDataSet GetFields(string id)
        {
            WellRow well = null;

            if (String.IsNullOrEmpty(id))
            {
                WellRow row = GroundWater.BusinessActions.Well.GetById(txtWellCode.Text.Trim(), false);
                if (row != null)
                {
                    return null;
                }

                well = (new InfoDataSet()).Wells.NewWellsRow();
                //well.Code = "";
                //well.Name = "";
                well.WaterSource = "dd";
                well.ResourceRegionCode = "dd";
                well.AdministrativeDivisionsCode = "dd";
                well.FunctionRegionCode = "ss";
                well.DesignYearlyWaterQuantity = 0m;
            }
            else
            {
                // update
                well = Well.GetById(id, false);
            }
            well.Name = txtWellName.Text;
            well.Code = txtWellCode.Text;
            well.Depth = Convert.ToDecimal(txtDepth.Text) ;

            well.Longitude = Convert.ToDecimal(txtLongitude.Text);
            well.Latitude = Convert.ToDecimal(txtLatitude.Text);
            if (txtShaftSinkingDate.Text.Length > 0)
            {
                well.ShaftSinkingDate = DateTime.Parse(txtShaftSinkingDate.Text);
            }
            well.SIMCard = txtSIMCard.Text;
            well.BTUAddress = txtBTUAddress.Text;
            well.SectionPlane = txtSectionPlane.Text;

            well.AdministrativeDivisionsCode = txtAdministrativeDivisionsCode.Text;
            well.DesignYearlyWaterQuantity = Convert.ToDecimal(txtDesignYearlyWaterQuantity.Text);
            well.FunctionRegionCode = txtFunctionRegionCode.Text;
            well.ResourceRegionCode = txtResourceRegionCode.Text;
            well.WaterSource = txtWaterSource.Text;

            well.Administration = txtAdministration.Text;
            if (txtDesignFlowRate.Text.Length > 0)
            {
                well.DesignFlowRate = Convert.ToDecimal(txtDesignFlowRate.Text);
            }
            if (txtDiameter.Text.Length > 0)
            {
                well.Diameter = Convert.ToDecimal(txtDiameter.Text);
            }
            if (txtDynamicLevel.Text.Length > 0)
            {
                well.DynamicLevel = Convert.ToDecimal(txtDynamicLevel.Text);
            }

            well.Landform = txtLandform.Text;
            well.ProjectRuningState = txtProjectRuningState.Text;
            well.PumpType = txtPumpType.Text;
            well.RemoveEquipment = txtRemoveEquipment.Text;
            if (txtStaticLevel.Text.Length > 0)
            {
                well.StaticLevel = Convert.ToDecimal(txtStaticLevel.Text);
            }

            if (txtAltitude.Text.Length > 0) 
            {
                well.Altitude = Convert.ToDecimal(txtAltitude.Text);
            }
            if (txtSequenceNumber.Text.Length > 0) 
            {
                well.SequenceNumber = Convert.ToInt32(txtSequenceNumber.Text);
            }
            well.WaterQuality = txtWaterQuality.Text;

            if(txtMaximumWaterlevel.Text.Length > 0)
            {
                well.MaximumWaterlevel = Convert.ToDecimal(txtMaximumWaterlevel.Text);
            }
            if (txtMinimumWaterlevel.Text.Length > 0)
            {
                well.MinimumWaterlevel = Convert.ToDecimal(txtMinimumWaterlevel.Text);
            }

            if (String.IsNullOrEmpty(id))
            {
                well.Table.Rows.Add(well);
            }
            else
            {
                
            }

            return well.Table.DataSet as InfoDataSet;
        }
    }

}
